// lib/providers/home_list_provider.dart
import 'package:app_router_demo/pages/home/models/home_list_model.dart';
import 'package:app_router_demo/services/http_service.dart';
import 'package:flutter/material.dart';

class HomeListProvider with ChangeNotifier {
  final HttpService _httpService = HttpService();

  List<HomeListModel> _items = [];
  int _currentPage = 1;
  bool _isLoading = false;
  bool _hasMore = true;
  String? _errorMessage;

  bool _isList = false;

  List<HomeListModel> get items => _items;
  bool get isLoading => _isLoading;
  bool get hasMore => _hasMore;
  String? get errorMessage => _errorMessage;
  bool get isList => _isList;

  HomeListProvider() {
    _httpService.initialize().then((_) {
      fetchItems(isRefresh: true);
    });
  }

  // 新增方法：用于在外部修改 _isList 的值
  void setIsList(bool value) {
    if (_isList != value) {
      _isList = value;
      notifyListeners(); // 通知 UI 更新
    }
  }

  Future<void> fetchItems({bool isRefresh = false}) async {
    if (_isLoading && !isRefresh) return;
    if (!_hasMore && !isRefresh) return;

    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    if (isRefresh) {
      _currentPage = 1;
      _hasMore = true;
      _items = [];
    }

    try {
      // 这里是关键：ApiResponse 的泛型直接是 List<HomeListModel>
      final response = await _httpService.get<List<HomeListModel>>(
        '/api/v1/data/recommend_user_list',
        queryParameters: {'page': _currentPage, 'pageSize': 10},
        // fromJson 函数的参数 (rawJsonData) 将是服务器响应中 "data" 字段的值 (即列表本身)
        fromJson: (rawJsonData) {
          // 确保 rawJsonData 是一个 List<dynamic>
          if (rawJsonData is List) {
            return rawJsonData
                .map((e) => HomeListModel.fromJson(e as Map<String, dynamic>))
                .toList();
          }
          // 如果 rawJsonData 不是 List，说明服务器返回的 data 字段不是列表，这里可以抛出错误或返回空列表
          debugPrint(
            'Warning: "data" field in API response is not a List. Received: $rawJsonData',
          );
          return [];
        },
      );

      if (response.success && response.data != null) {
        if (isRefresh) {
          _items = response.data!;
        } else {
          _items.addAll(response.data!);
        }

        // 直接从 ApiResponse 中获取 count 和 current
        final totalItems = response.count ?? 0;
        final currentPage =
            response.current ??
            _currentPage; // 使用 response.current，如果没有则用当前的 _currentPage

        // 判断是否有更多数据：当前页 * 每页数量 < 总数
        // 需要知道每页的数量，假设是10
        final int pageSize = 10;
        _hasMore = (currentPage * pageSize) < totalItems;

        if (_hasMore) {
          _currentPage++; // 只有在有更多数据时才递增页码
        }
      } else {
        _errorMessage = response.message;
        debugPrint('获取数据失败: ${response.message}');
      }
    } catch (e) {
      _errorMessage = e.toString();
      debugPrint('请求发生异常: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
}
